package com.boat.starter.jetcache.util;

import java.util.concurrent.TimeUnit;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.support.SimpleCacheManager;
import com.boat.starter.jetcache.service.JetcacheContext;

import lombok.extern.slf4j.Slf4j;

/**
 * 缓存门面
 * @author 周江
 *
 */
@Slf4j
public class CacheUtils {
	public static void put(String cacheName, Object key, Object value, int expire, TimeUnit unit) {
		Cache cache = getCache(cacheName);
		if (cache == null) {
			log.warn("没有找到指定的cacheName:{}, 请检查！",cacheName);
		}else {
			cache.put(key, value, expire, unit);
		}
	}

	public static <T> T get(String cacheName, Object key) {
		Cache cache = getCache(cacheName);
		if (cache == null) {
			log.warn("没有找到指定的cacheName:{}, 请检查！",cacheName);
			return null;
		}else {
			return (T) cache.get(key);
		}
	}
	
	public static Boolean remove(String cacheName, Object key) {
		Cache cache = getCache(cacheName);
		if (cache == null) {
			log.warn("没有找到指定的cacheName:{}, 请检查！",cacheName);
			return false;
		}else {
			return cache.remove(key);
		}
	}
	
	public static Cache getCache(String cacheName) {
		try {
			SimpleCacheManager cacheManager = JetcacheContext.getSpringConfigProvider().getCacheManager();
			return cacheManager.getCache(cacheName);
		}catch(Exception ex) {
			log.warn("不能正确获取当前缓存，cacheName: {},错误消息: {}", cacheName, ex.getMessage());
			return null;
		}
	}
}
